﻿#region 命名空间

using System;
using System.Collections.Specialized;
using System.Data.Entity.Validation;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;

using WinnerCMS.Common;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 异常的处理类
    /// </summary>
    [ConfigurationElementType(typeof (CustomCallHandlerData))]
    public class ExceptionCallHandler : ICallHandler
    {
        public int Order { get; set; }

        /// <summary>
        /// 异常的处理类
        /// </summary>
        /// <param name="order"></param>
        public ExceptionCallHandler(int order)
        {
            Order = order;
        }

        /// <summary>
        /// 构造函数，此处不可省略，否则会导致异常
        /// </summary>
        /// <param name="attributes">配置文件中所配置的参数</param>
        public ExceptionCallHandler(NameValueCollection attributes)
        {
            Order = Convert.ToInt32(attributes["Order"]);
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var result = getNext().Invoke(input, getNext);

            if (result.Exception != null)
            {
                if (((MethodInfo) (input.MethodBase)).ReturnType == typeof (Result))
                {
                    if (result.Exception is DbEntityValidationException)
                    {
                        var err = ((DbEntityValidationException) result.Exception);
                        LogHelper.Error(err);
                    }
                    else
                    {
                        LogHelper.Error(result.Exception);
                    }

                    Result res = new Result
                    {
                        Errors = result.Exception.Message
                    };

                    return input.CreateMethodReturn(res, input.Arguments);
                }

                //ExceptionPolicy.HandleException(ex, this.PolicyName);

                LogHelper.Error(result.Exception);
                throw result.Exception;
            }
            return result;
        }
    }
}